package com.youpai.platform.vulture.service.gateway;

import com.youpai.platform.vulture.service.constant.PortConstants;
import com.youpai.platform.vulture.service.gateway.initializer.TcpServerChildHandlerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @date: 2022/6/23 12:00
 * @author: Anna
 * @version: 1.0
 * @description: tcp服务
 */
@Slf4j
@Component
public class TcpServer {

    @Resource
    private TcpServerChildHandlerInitializer tcpServerChildHandlerInitializer;

    public void startTcpServer() {
        ChannelFuture channelFuture = null;
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workGroup = new NioEventLoopGroup();
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024) // 客户端连接请求所存放的队列大小
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .childOption(ChannelOption.TCP_NODELAY, true) // 关闭延迟发送
                    .childOption(ChannelOption.SO_KEEPALIVE, false) // 关闭链接保活，自定义心跳保活
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(32 * 1024, 64 * 1024))
                    .childHandler(tcpServerChildHandlerInitializer);
            channelFuture = serverBootstrap.bind(PortConstants.TCP_PORT).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (null == channelFuture) {
                log.error("tcp server start fail !");
            }
        }
    }
}
